package com.mjlf.shiro.realm;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.Assert;
import org.junit.Test;

/**
 * @ClassName Login
 * @auther mjlf
 * @Date 2019/6/10 14:00
 * @Description TODO
 */
public class Login {

    @Test
    public void testLogin(){

        //1.初始化SecurityManagerFactory 工具类，此处使用iniSecurityManagerFactory
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-realm.ini");

        //2.从SecurityManagerFactory工具类中获取SecurityManager实例
        SecurityManager securityManager = factory.getInstance();

        //3. 通过SecurityUtils设置securityManager
        SecurityUtils.setSecurityManager(securityManager);

        //4. 获取当前主体
        Subject subject = SecurityUtils.getSubject();

        //5.实例化登录认证token,此处使用账号/密码方式
        AuthenticationToken authenticationToken = new UsernamePasswordToken("zhang", "123");

        //6. 执行登录
        subject.login(authenticationToken);

        //获取认证通过的数量
        subject.getPrincipals().asList().forEach(System.out::println);

        //7. 验证登录
        Assert.assertEquals(true, subject.isAuthenticated());

        //8. 退出登录
        subject.logout();
    }
}
